<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true"  @register="registerDrawer"
    @ok="handleSubmit" @close="handleclose" width="40%">
    <!-- :okAuth="'proj:enex:pmApproach:edit'" -->
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProjXjPmInspectionForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicUpload } from '/@/components/Upload';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import { PmInspection, pmInspectionSave, pmInspectionForm } from '/@/api/proj/xj/pmInspection';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import {
    PmApproach, pmApproachSengEnMsg,
    pmApproachSengExMsg, pmApproachValidEn, pmApproachValidEx
  } from '/@/api/proj/enex/pmApproach';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();


  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('proj.enex.pmApproach');
  const { showMessage } = useMessage();
  const record = ref < PmApproach > ({} as PmApproach);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: status.value=='0' ? t('发送入场通知') : status.value=='1'?t('确认入场') : status.value=='2'?t('发送撤场通知')
    :t('确认撤场'),
  }));

  let status = ref<any>('0')

  // const inputFormSchemas: FormSchema[] = [
  //   {
  //     label: t('项目名称'),
  //     field: 'projectno',
  //     fieldLabel: 'name',
  //     component: 'TreeSelect',
  //     componentProps: {
  //       api: pmProjectinformationTreeData,
  //       params: {},
  //       canSelectParent: false,
  //       allowClear: false,
  //     },
  //   },
  //   {
  //     label: t('项目编号'),
  //     field: 'projectno',
  //     component: 'Input',
  //     componentProps: {
  //       maxlength: 50,
  //       readonly: true,
  //     },
  //     required: true,
  //   },
  //   {
  //     label: t('通知进场日期：'),
  //     field: 'inspectiondate',
  //     component: 'DatePicker',
  //     componentProps: {
  //       format: 'YYYY-MM-DD',
  //     },
  //     required: true,
  //   },

  //   // {
  //   //   label: t('巡检备注'),
  //   //   field: 'remarks',
  //   //   component: 'InputTextArea',
  //   //   componentProps: {
  //   //     maxlength: -1,
  //   //     rows: 5,
  //   //   },
  //   //   colProps: { lg: 24, md: 24 },
  //   // },
  //   // {
  //   //   label: t('图片上传'),
  //   //   field: 'dataMap',
  //   //   component: 'Upload',
  //   //   componentProps: {
  //   //     loadTime: computed(() => record.value.__t),
  //   //     bizKey: computed(() => record.value.id),
  //   //     bizType: 'pmInspection_image',
  //   //     uploadType: 'image',
  //   //   },
  //   //   colProps: { lg: 24, md: 24 },
  //   // },
  // ];

  // const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  //   labelWidth: 120,
  //   schemas: inputFormSchemas,
  //   baseColProps: { lg: 12, md: 24 },
  // });

  const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    // const res = await pmInspectionForm(data);
    record.value = data
    record.value.__t = new Date().getTime();
    status.value = data.status

    var myDate = new Date();
    let y = myDate.getFullYear();
    let m = myDate.getMonth()+1<10? `0${myDate.getMonth()+1}`: myDate.getMonth()+1;
    let d = myDate.getDate()<10? `0${myDate.getDate()}`: myDate.getDate();
    let dateFlag=`${y}-${m}-${d}`

    let inputFormSchemas: FormSchema[] = [];
    if (data.status == '0') {
      record.value.predate = dateFlag
      record.value.pcode = userStore.getProjecte.code
      record.value.name = userStore.getProjecte.name
      
      inputFormSchemas = [
        {
          label: t('项目名称'),
          field: 'pcode',
          fieldLabel: 'name',
          component: 'TreeSelect',
          componentProps: {
            api: pmProjectinformationTreeData,
            params: {},
            canSelectParent: false,
            allowClear: false,
          },
          itemProps:{ validateTrigger: 'blur' },
          required: true,
        },
        {
          label: t('项目编号'),
          field: 'pcode',
          component: 'Input',
          dynamicDisabled: true,
          componentProps: {
            maxlength: 50,
            // readonly: true,
          },
          required: true,
        },
        {
          label: t('要求进场'),
          field: 'predate',
          component: 'DatePicker',
          componentProps: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
          required: true,
        },
        // {
        //   label: t('图片上传'),
        //   field: 'dataMap',
        //   component: 'Upload',
        //   componentProps: {
        //     loadTime: computed(() => record.value.__t),
        //     bizKey: computed(() => record.value.id),
        //     bizType: 'pmInspection_image',
        //     uploadType: 'image',
        //   },
        //   colProps: { lg: 24, md: 24 },
        // },
      ];
    }
    if (data.status == '1') {
      record.value.approachdate = dateFlag
      inputFormSchemas = [
        {
          label: t('项目名称'),
          field: 'pcode',
          fieldLabel: 'name',
          component: 'TreeSelect',
          dynamicDisabled: true,
          componentProps: {
            api: pmProjectinformationTreeData,
            params: {},
            canSelectParent: false,
            allowClear: false,
          },
          itemProps:{ validateTrigger: 'blur' },
          required: true,
        },
        {
          label: t('项目编号'),
          field: 'pcode',
          component: 'Input',
          dynamicDisabled: true,
          componentProps: {
            maxlength: 50,
            // readonly: true,
          },
          required: true,
        },
        {
          label: t('确认进场'),
          field: 'approachdate',
          component: 'DatePicker',
          dynamicDisabled: true,
          componentProps: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
          required: true,
        },
        {
          label: t('现场图（进）'),
          field: 'dataMap',
          component: 'Upload',
          componentProps: {
            loadTime: computed(() => record.value.__t),
            bizKey: computed(() => record.value.id),
            bizType: 'pmApproachEN_image',
            uploadType: 'image',
            isPreview: true
          },
          colProps: { lg: 24, md: 24 },
        },
      ];
    }
    if (data.status == '2') {
      record.value.prewithdrawdate = dateFlag
      inputFormSchemas = [
        {
          label: t('项目名称'),
          field: 'pcode',
          fieldLabel: 'name',
          component: 'TreeSelect',
          dynamicDisabled: true,
          componentProps: {
            api: pmProjectinformationTreeData,
            params: {},
            canSelectParent: false,
            allowClear: false,
          },
          itemProps:{ validateTrigger: 'blur' },
          required: true,
        },
        {
          label: t('项目编号'),
          field: 'pcode',
          component: 'Input',
          dynamicDisabled: true,
          componentProps: {
            maxlength: 50,
            // readonly: true,
          },
          required: true,
        },
        {
          label: t('要求撤场'),
          field: 'prewithdrawdate',
          component: 'DatePicker',
          componentProps: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
          required: true,
        },
      ];
    }
    if (data.status == '3') {
      record.value.withdrawdate = dateFlag
      inputFormSchemas = [
        {
          label: t('项目名称'),
          field: 'pcode',
          fieldLabel: 'name',
          component: 'TreeSelect',
          dynamicDisabled: true,
          componentProps: {
            api: pmProjectinformationTreeData,
            params: {},
            canSelectParent: false,
            allowClear: false,
          },
          itemProps:{ validateTrigger: 'blur' },
          required: true,
        },
        {
          label: t('项目编号'),
          field: 'pcode',
          component: 'Input',
          dynamicDisabled: true,
          componentProps: {
            maxlength: 50,
            // readonly: true,
          },
          required: true,
        },
        {
          label: t('确认撤场'),
          field: 'withdrawdate',
          component: 'DatePicker',
          dynamicDisabled: true,
          componentProps: {
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
          },
          required: true,
        },
        {
          label: t('现场图（撤）'),
          field: 'dataMap',
          component: 'Upload',
          componentProps: {
            loadTime: computed(() => record.value.__t),
            bizKey: computed(() => record.value.id),
            bizType: 'pmApproachEX_image',
            uploadType: 'image',
            isPreview: true
          },
          colProps: { lg: 24, md: 24 },
        },
      ];
    }
   await setProps({
      labelWidth: 150,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });
    console.log(record.value);
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  function handleclose(){
    emit('success', {});
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });


      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id?record.value.id:'',
        ...data
      };

      if (status.value == '0') {
       const res = await pmApproachSengEnMsg(params);
        showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
      if (status.value == '1') {
       const res = await pmApproachValidEn(params);
       showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
      if (status.value == '2') {
       const res = await pmApproachSengExMsg(params);
       showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
      if (status.value == '3') {
       const res = await pmApproachValidEx(params);
       showMessage(res.message);
        setTimeout(closeDrawer);
        emit('success', data);
      }
     
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  /deep/.jeesite-basic-table .ant-table-content {
    min-height: 40vh;
  }
</style>